<template>
    <div class="upload">
        <el-form ref="form" :model="form" label-width="80px">
            <template v-for="item in defaultList">
                <el-form-item label="第1层">
                    <input type="file" :id="`file_input${item.id}`" style="display: none;"
                        @change="fileUpload($event, item.text)">
                    <div class="file_com">
                        <!-- code -->
                        <div class="file_com_items">
                            <el-input :value="item.id" :disabled="true" style="width:100px;">
                            </el-input>
                        </div>
                        <!-- file -->
                        <div class="file_com_items">
                            <el-button type="primary" size="small" @click="openUpload(item.id, item.text)">上传</el-button>
                        </div>
                        <!-- color -->
                        <mutipleColor :value="item.color" :item="genomeItem" @changeList="changeList" />
                    </div>
                </el-form-item>
            </template>

            <el-form-item label="色 系">
                <mutipleColor v-on="$listeners" v-bind="$attrs" :value="item.default" :item="item"
                    @changeList="changeList" />
            </el-form-item>

            <div ref="sortRef">
                <template v-for="(item, index) in fileList">
                    <div>
                        <el-form-item :label="`第${index + 2}层`">
                            <input type="file" :id="`file_input${item.id}`" style="display: none;"
                                @change="fileUpload($event, item.id)">
                            <div class="file_com">
                                <!-- code -->
                                <div class="file_com_items">
                                    <el-select v-model="item.text" filterable allow-create default-first-option
                                        popper-class="file" style="width: 100px;" placeholder="code"
                                        @change="addSelect(index, item.text)">
                                        <el-option v-for="a in codeOptions" :key="a.value" :label="a.label" :value="a.value"
                                            :disabled="setDisabled(a)">
                                        </el-option>
                                    </el-select>
                                </div>
                                <!-- file -->
                                <div class="file_com_items">
                                    <el-button type="primary" size="small"
                                        @click="openUpload(item.id, item.text)">上传</el-button>
                                </div>
                                <!-- color -->
                                <template v-if="item.type !== 'heatmap'">
                                    <el-color-picker v-model="item.color" show-alpha
                                        class="file_com_items"></el-color-picker>
                                </template>
                                <template v-else>
                                    <el-color-picker v-model="item.hotColor1" show-alpha
                                        class="file_com_items"></el-color-picker>
                                    <el-color-picker v-model="item.hotColor2" show-alpha
                                        class="file_com_items"></el-color-picker>
                                </template>
                                <!-- type -->
                                <div class="file_com_items">
                                    <el-select v-model="item.type" style="width: 100px;">
                                        <el-option :value="item.value" :label="item.label"
                                            v-for="(item, index) in typeOptions" :key="index">
                                            <!-- <i class="iconfont icon-zhexiantu1" style="color: #000;"></i>
                            <span style="margin-left: 10px;">折线</span> -->
                                        </el-option>
                                        <!-- <el-option value="straight" label="直线">
                            <i class="iconfont icon-jiangefuhao" style="color: #000;"></i>
                            <span style="margin-left: 10px;">直线</span>
                        </el-option>
                        <el-option value="point" label="点线">
                            <i class="iconfont icon-qita" style="color: #000;"></i>
                            <span style="margin-left: 10px;">点线</span>
                        </el-option> -->
                                    </el-select>
                                </div>
                                <!-- add -->
                                <div class="file_com_items">
                                    <!-- 新增 -->
                                    <el-button size="small" icon="el-icon-plus" style="padding: 9px;" @click="addItem"
                                        v-if="index === 0"></el-button>
                                    <!-- 删除 -->
                                    <el-button size="small" icon="el-icon-delete" style="padding: 9px;"
                                        @click="delItem(item.id)" v-else></el-button>
                                </div>
                            </div>
                        </el-form-item>
                        <el-form-item label="半径">
                            <div style="display:flex;">
                                <div style="width:320px;margin-right:20px;">
                                    <el-slider v-model="item.slider" :max="1" :min="0" :step="0.01"
                                        @change="changeFirst($event, index)"></el-slider>
                                </div>
                                <div>
                                    <el-tooltip class="item" effect="dark" content="固定半径" placement="top">
                                        <el-checkbox v-model="item.check"></el-checkbox>
                                    </el-tooltip>
                                </div>
                            </div>
                        </el-form-item>
                    </div>
                </template>
            </div>
            
            <el-button type="primary" class="primary_static_btn" @click="startDraw">开始绘图</el-button>
        </el-form>
    </div>
</template>

<script>
import Sortable from 'sortablejs';
import mutipleColor from './mutipleColor.vue'
import { deepClone } from '@/utils';
import { uploadRingGraphFileRequest } from '@/api/ringGraph'
export default {
    name: 'GenescloudUiUpload',
    components: {
        mutipleColor
    },
    data() {
        return {
            num: 1,
            selectList: this.$publicData('colorList'),
            form: {},
            item: {
                code: 'default',
                default: 'Science',
                data: []
            },
            genomeItem: { code: 'genome', default: 'Science', data: [] },
            colorOptions: this.$publicData('colorList'),
            codeOptions: [],
            file: '',
            defaultList: [
                {
                    id: 'genome',
                    text: 'genome',
                    file: '',
                    color: 'Science'
                }
            ],
            fileList: [
                {
                    id: 'default',
                    text: '',
                    file: '',
                    color: '#3a4892',
                    hotColor1: '#5d04f7',
                    hotColor2: '#fb0212',
                    type: 'line',
                    slider: 1,
                    check: false
                }
            ],
            typeOptions: [
                {
                    label: '散点图',
                    value: 'scatter',
                },
                {
                    label: '折线图',
                    value: 'line',
                },
                {
                    label: '直方图',
                    value: 'histogram',
                },
                {
                    label: '热图',
                    value: 'heatmap',
                },
                {
                    label: '标记文字',
                    value: 'text',
                },
                {
                    label: '片状图',
                    value: 'tile',
                }
            ]
        };
    },
    watch: {
        fileList: {
            handler(val, newVal) {
                if (!val) return
                this.item.data = deepClone(val)
            },
            immediate: true,
            deep: true
        }
    },
    computed: {
        setDisabled() {
            return function (opt, list) {
                // opt为每项option，index为el-select索引
                // 全部已选择
                const selectedArr = this.fileList.reduce((pre, item, index) => {
                    pre.push(item.text)
                    return pre
                }, [])
                // 删除自己的已选
                //   selectedArr.splice(index, 1)
                // 其它的已选，禁用
                return selectedArr.includes(opt.value)
            }
        }
    },
    mounted() {
        this.sortDrag()
    },

    methods: {
        addItem() {
            const list = this.selectList.find(i => i.value === this.genomeItem.default).content
            const id = new Date().getTime()
            this.fileList.push({
                id,
                text: '',
                file: '',
                color: list[this.num],
                hotColor1: '#5d04f7',
                hotColor2: '#fb0212',
                type: 'line',
                slider: this.computeSlider(),
                check: false
            })
            this.fileList.map((item, index) => {
                if (!item.check) {
                    item.slider = this.computeSlider()
                }
            })
            this.num++
        },
        computeSlider() {
            let arr = deepClone(this.fileList)
            let total = arr.reduce((pre, item, index) => {
                if (item.check) {
                    pre += item.slider
                }
                return pre
            }, 0)
            return Number((((1 - total) / (this.fileList.length))).toFixed(2))
        },
        delItem(id) {
            const index = this.fileList.findIndex(i => i.id === id)
            this.fileList.splice(index, 1)
        },
        openUpload(id, text) {
            if (!text) return this.$message.error('请先选择或者输入code!')
            document.querySelector(`#file_input${id}`).click()
        },
        async fileUpload(e, id) {
            let item
            if (id === 'genome') {
                item = this.defaultList[0]
            } else {
                item = this.fileList.find(i => i.id === id)
            }
            item.file = e.target.files[0];
            if (!item.file) return
            const tsv = item.file.name.split('.')[1] !== 'tsv'
            const txt = item.file.name.split('.')[1] !== 'txt'
            const csv = item.file.name.split('.')[1] !== 'csv'
            const xls = item.file.name.split('.')[1] !== 'xls'
            const xlsx = item.file.name.split('.')[1] !== 'xlsx'
            if (tsv && txt && csv && xls && xlsx) return this.$message.error('暂不支持该文件格式！')
            const formData = new FormData();
            formData.append('file', item.file);
            const res = await uploadRingGraphFileRequest('ringGraph', id, formData)
            if (res.code !== 200) return this.$message.error(res.message)
            this.$message({ type: 'success', message: res.message })
            item.file = res.data.recordId
            //允许上传同一个文件
            e.srcElement.value = ""
        },
        //改变颜色
        changeList(code, value, list) {
            if (code === 'genome') {
                let item = this.defaultList.find(i => i.id === code)
                item.color = value
                this.genomeItem.default = value
            } else {
                this.item.default = value
                this.fileList = deepClone(list)
            }
        },
        //新增下拉框输入
        addSelect(index, text) {
            if (this.codeOptions.find(i => i.value === text)) return
            this.$nextTick(() => {
                this.codeOptions.push({
                    lebel: this.fileList[index].text,
                    value: this.fileList[index].text
                })
            });
        },
        //开始绘图
        startDraw() {
            if (!this.fileList.every(i => i.text)) return this.$message.error('请确保code都已填写!')
            let item = this.defaultList.concat(this.fileList)
            this.$emit('startDraw', item)
        },
        sortDrag() {
            let self = this
            // 这里的nextTick可以不用，但如果是弹框弹出来，在弹框里排序，弹框关闭就销毁，那还是要的，这时初始化就不要放在mounted中，放在开启弹框的方法中
            this.$nextTick(() => {
                let el = this.$refs.sortRef
                new Sortable(el, {
                    animation: 150,
                    filter: '.sort-none',
                    onStart() { },
                    onEnd(evt) {
                        // 对数组排序进行调整
                        self.fileList.splice(evt.newIndex, 0, self.fileList.splice(evt.oldIndex, 1)[0])
                        let newArray = self.fileList.slice(0)
                        self.fileList = []
                        self.$nextTick(() => {
                            self.fileList = newArray
                        })
                    }
                })
            })
        },
        changeFirst(value, index) {
            this.fileList[index].check = false
            let arr = deepClone(this.fileList)
            let num = 1
            let total = arr.reduce((pre, item, index) => {
                if (item.check) {
                    pre += item.slider
                }
                return pre
            }, 0)
            let checkLength = 0
            arr.forEach((item, i) => {
                if (!item.check && i !== index) {
                    checkLength++
                }
            })
            let now = this.fileList[index].slider
            console.log(num, total, now, 'sss');
            if (Number((((num - total - now) / checkLength)).toFixed(2)) < 0) {
                this.fileList[index].slider = 0
                return this.$message.error('剩余空间不足,请重新调整！')
            }
            this.fileList.map((item, i) => {
                if (!item.check && i !== index) {
                    item.slider = Number((((num - total - now) / checkLength)).toFixed(2))
                }
            })
        }
    },
};
</script>

<style lang="scss" scoped>
.upload {
    ::v-deep .el-input {
        height: 36px;
        line-height: 36px;

        .el-input__inner {
            border-radius: 6px;
            height: 36px;
        }

        .el-input__icon {
            line-height: 36px;
        }
    }

    .file_com {
        display: flex;
        align-items: center;

        .file_com_items {
            margin-right: 5px;
        }
    }

    .primary_static_btn {
        // position: absolute;
        // bottom: 0;
        // right: 25px;
        border-radius: 18px;
        margin: 15px 15px 0 0;
        float: right;
    }
}
</style>